package com.zqu.ordersystem.controller;

import com.zqu.ordersystem.entity.Result;
import com.zqu.ordersystem.service.FileUploadService;
import com.zqu.ordersystem.utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@CrossOrigin(origins = "http://localhost:8888", allowedHeaders = "*", methods = {RequestMethod.POST, RequestMethod.OPTIONS}, allowCredentials = "true")
@Slf4j
@RequestMapping("/upload")
public class FileUploadController {

    @Autowired
    private FileUploadService fileUploadService;

    // 上传用户头像
    @PostMapping("/avatar")
    public Result uploadAvatar(@RequestParam("file") MultipartFile file, HttpServletRequest req) {
        String token = req.getHeader("Authorization");
        Integer userId = Integer.valueOf(JwtUtils.getAudience(token));
        String avatarUrl = fileUploadService.uploadAvatar(userId, file);
        return new Result(avatarUrl, "头像上传成功", 200);
    }

    // 上传食品图片
    @PostMapping("/dish")
    public Result uploadDishImage(@RequestParam("file") MultipartFile file, @RequestParam("dishId") Integer dishId, HttpServletRequest req) {
        String token = req.getHeader("Authorization");
        JwtUtils.verifyToken(token); // 验证token但不使用用户ID
        String imageUrl = fileUploadService.uploadDishImage(dishId, file);
        return new Result(imageUrl, "食品图片上传成功", 200);
    }
}
